package framework.mybatis.xml.dao;

import framework.mybatis.xml.entity.User;
import framework.mybatis.xml.entity.UserVO;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class UserDao {

    private SqlSessionFactory getSqlSessionFactory() throws IOException {
        String resource = "framework/mybatis/xml/config-xml.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        // SqlSessionFactory 对应一个 environment
        return new SqlSessionFactoryBuilder().build(inputStream);
    }

    public void createTable() throws IOException {
        try (SqlSession session = getSqlSessionFactory().openSession()) {
            Object result = session.update("framework.mybatis.xml.UserMapperXml.createTable");
            System.out.println(result);
        }
    }

    public User getUser(User user) throws IOException {
        try (SqlSession session = getSqlSessionFactory().openSession()) {
            user = session.selectOne("framework.mybatis.xml.UserMapperXml.selectUser", user);
            return user;
        }
    }

    public UserVO getUserVO(User user) throws IOException {
        try (SqlSession session = getSqlSessionFactory().openSession()) {
            return session.selectOne("framework.mybatis.xml.UserMapperXml.selectUserVO", user);
        }
    }

    public int insert(User user) throws IOException {
        try (SqlSession session = getSqlSessionFactory().openSession()) {
            int result = session.insert("framework.mybatis.xml.UserMapperXml.addUser", user);
            session.commit();
            return result;
        }
    }

    public int update(User user) throws IOException {
        try (SqlSession session = getSqlSessionFactory().openSession()) {
            int result = session.update("framework.mybatis.xml.UserMapperXml.updateUser", user);
            session.commit();
            return result;
        }
    }

    public int delete(User user) throws IOException {
        try (SqlSession session = getSqlSessionFactory().openSession()) {
            int result = session.delete("framework.mybatis.xml.UserMapperXml.delUser", user);
            session.commit();
            return result;
        }
    }

}
